<template>
  <el-row class="login-container" justify="center" :align="'middle'">
    <el-card style="max-width: 480px">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" alt="" />
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="handleChange">
          {{ formType ? "返回登录" : "注册账号" }}
        </el-link>
      </div>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="0"
      >
        <el-form-item prop="userName">
          <el-input
            v-model="loginForm.userName"
            placeholder="手机号"
            prefix-icon="UserFilled"
          />
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input
            v-model="loginForm.passWord"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
          />
        </el-form-item>
        <el-form-item prop="validCode" v-if="formType">
          <el-input
            v-model="loginForm.validCode"
            placeholder="验证码"
            prefix-icon="Lock"
          >
            <template #append>
              <span @click="countdownChange">{{ countdown.validText }}</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%"
            @click="submitForm(loginFormRef)"
          >
            {{ formType ? "注册账号" : "登录" }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<script setup>
import { reactive, ref, computed, toRaw } from "vue";
import { useRouter } from "vue-router";
import { useStore } from 'vuex';
import { getCodeApi, userAuthenticationApi, loginApi, getMenuPermissionsApi } from "../../api/index";
const imgUrl = new URL("../../assets/login_bg.png", import.meta.url).href;

const router = useRouter();
const store = useStore()

const routerList = computed(() => store.state.menu.routerList)

// 切换表单0登录 1注册
const formType = ref(0);

// 点击切换登录和注册
const handleChange = () => {
  formType.value = formType.value ? 0 : 1;
};

// 发送验证码
const countdown = reactive({
  validText: "获取验证码",
  time: 10,
});

/**
 * 表单数据模块
 */
const loginForm = reactive({
  userName: "",
  passWord: "",
  validCode: "",
});

let flag = false;
let timer = null;
const countdownChange = async () => {
  if (flag) return;
  //判断手机号是否正确
  const phoneReg = /^1[3-9]\d{9}$/;
  if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
    return ElMessage({
      message: "手机号格式不正确",
      type: "warning",
    });
  }
  timer = setInterval(() => {
    if (countdown.time <= 0) {
      countdown.time = 60;
      countdown.validText = `获取验证码`;
      flag = false;
      clearInterval(timer);
      timer = null;
    } else {
      countdown.time -= 1;
      countdown.validText = `${countdown.time}s`;
    }
  }, 1000);
  flag = true;
  const { code, data, msg } = await getCodeApi({ tel: loginForm.userName });
  if (code === 10000) {
    ElMessage.success(msg);
  }
};

const validateUser = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入账号"));
  } else {
    callback();
  }
};

const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    callback();
  }
};

const validCodeValid = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入验证码"));
  } else {
    callback();
  }
};

const rules = reactive({
  userName: [{ validator: validateUser, trigger: "blur" }],
  passWord: [{ validator: validatePass, trigger: "blur" }],
  validCode: [{ validator: validCodeValid, trigger: "blur" }],
});

// 表单提交
const loginFormRef = ref();

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      // 注册页面
      if (formType.value) {
        const { code, data, message } = await userAuthenticationApi(loginForm);
        if (code === 10000) {
          ElMessage.success(message?.msg || message);
          formType.value = 0;
        }
      } else {
        const { code, data, message } = await loginApi(loginForm);
        if (code === 10000) {
          ElMessage.success(message);
          const { token, userInfo } = data;
          localStorage.setItem("pz_token", token);
          localStorage.setItem("pz_userInfo", JSON.stringify(userInfo));
          getPermissions()
        }
      }
    } else {
      console.log("error submit!");
    }
  });
};

/** 获取菜单权限 */
const getPermissions = async () => {
  const { code, data } = await getMenuPermissionsApi({})
  if (code === 10000) {
    store.commit('dnamicMenu', {
      payload: data,
      router
    })
    // toRaw(routerList.value).forEach(item => {
    //   router.addRoute('main', item)
    // })
    router.push("/");
  }
}
</script>

<style lang="less" scoped>
:deep(.el-card__header) {
  padding: 0;
}
.login-container {
  height: 100%;

  .card-header {
    background: #899fe1;

    img {
      width: 430px;
    }
  }

  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
}
</style>